package com.android.webframework;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

public class GoogleDirections extends DirectionsService {

	
	/**
	 * Argument GoogleDirections constructor
	 * @param requestOb takes in a request object
	 */
	public GoogleDirections(RequestObject requestOb) {
		servicesLog.setLogTag(logTag);
		this.requestOb = requestOb;
	}
	
	/**
	 * Request a service
	 * @return a response object
	 * @see ResponseObject
	 */
	public ResponseObject request() throws RequestException {
		ArrayList<Step> directions = new ArrayList<Step>();
		
		String jsonResponse = processJsonRequest();
		try {
			JSONObject jsonObject = new JSONObject(jsonResponse);
			String statusCode = jsonObject.getString("status");
			
			// Check the response status before proceeding
			if (statusCode.equals("OK")) {
				// Update the log with the status code
				servicesLog.appendToLog("Status:" + statusCode);
				
				// Always choose the first route available
				JSONObject route = (JSONObject)((JSONArray)jsonObject.getJSONArray("routes")).get(0);
				
				// There will always be only one leg
				JSONObject leg = (JSONObject)((JSONArray)route.getJSONArray("legs")).get(0);
				
				// Get all of the steps
				JSONArray steps = (JSONArray)leg.getJSONArray("steps");
				
				// Add information from each step into the directions ArrayList
				for (int i = 0; i < steps.length(); i++) {
					JSONObject step = steps.getJSONObject(i);
					
					// Extract the instruction string
					String instruction = removeHTML(step.getString("html_instructions"));
					
					// Extract the start location 
					JSONObject start_loc = step.getJSONObject("start_location");
						// Extract latitude
					double latitude = start_loc.getDouble("lat");
						// Extract longitude
					double longitude = start_loc.getDouble("lng");
						// Add values into a primitive array
					double[] start = { latitude, longitude };
					
					// Extract the end location
					JSONObject end_loc = step.getJSONObject("end_location");
						// Extract latitude
					latitude = end_loc.getDouble("lat");
						// Extract longitude
					longitude = end_loc.getDouble("lng");
						// Add values into a primitive array
					double[] end = { latitude, longitude };
					
					directions.add(new Step(instruction, start, end));
					
					// Update the log with the newly added instruction
					servicesLog.appendToLog("Added instruction: " + instruction);
				}
			}
			else {
				servicesLog.appendToLog("Error: " + statusCode);
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return new ResponseObject(directions);
	}
}
